// 阿里云短信发送工具类
import Dysmsapi, * as $Dysmsapi from '@alicloud/dysmsapi20170525';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
import Util from '@alicloud/tea-util';
import * as $tea from '@alicloud/tea-typescript';
import { ConfigService } from '@nestjs/config';
import { CacheEnum } from '../../common/enum';

// 短信发送结果类型定义
export interface SmsResult {
  success: boolean;
  message?: string;
  requestId?: string;
  bizId?: string;
}

export default class SmsSender {
  private client: Dysmsapi;

  /**
   * 构造函数，初始化短信客户端
   * @param configService
   */
  constructor(private readonly configService: ConfigService) {
    const config = new $OpenApi.Config({});
    config.accessKeyId = this.configService.get('aliyun.accessKeyId');
    config.accessKeySecret = this.configService.get('aliyun.accessKeySecret');
    this.client = new Dysmsapi(config);
  }

  /**
   * 发送短信
   * @param phoneNumbers 接收短信的手机号码，多个号码用逗号分隔
   * @param signName 短信签名名称
   * @param templateCode 短信模板CODE
   * @param templateParam 短信模板变量对应的实际值，JSON格式字符串
   * @returns 短信发送结果
   */
  async sendSms(phoneNumbers: string, signName: string, templateCode: string, templateParam: string): Promise<SmsResult> {
    try {
      const sendReq = new $Dysmsapi.SendSmsRequest({
        phoneNumbers,
        signName,
        templateCode,
        templateParam,
      });

      const sendResp = await this.client.sendSms(sendReq);
      const code = sendResp.body.code;

      if (Util.equalString(code, 'OK')) {
        return {
          success: true,
          requestId: sendResp.body.requestId,
          bizId: sendResp.body.bizId,
          message: '短信发送成功',
        };
      } else {
        return {
          success: false,
          requestId: sendResp.body.requestId,
          message: `短信发送失败: ${sendResp.body.message}`,
        };
      }
    } catch (error) {
      const err = error as Error;
      return {
        success: false,
        message: `发送过程出错: ${err.message}`,
      };
    }
  }
}
